<template>
  <div>
    <label for="fileInput">
      <div class="img">
        <div id="Box">
          <img :src="ImgSrc" alt="头像上传" />
        </div>
        <button @click="uploadAvatar">上传</button>
      </div>
    </label>
    <div class="username">
      <input type="file" ref="input" @change="showPicture()" id="fileInput" />
    </div>
  </div>
</template>

<script setup lang="ts">
import Bus from "../bus";
import { ref, defineEmits, computed, reactive } from "vue";
import { useUserStore } from "@/store";
import $axios from "@/http";
const store = useUserStore();
const ImgSrc = ref<string>("");

const input = ref<HTMLInputElement | null>(null);
const uploadAvatar = () => {
  if (input.value?.files && input.value?.files[0]) {
    if (input.value?.files[0].size / 1024 > 2000) {
      alert("文件大小不能超过2m");
      Bus.$emit("finishChange", "error");
      return false;
    }
    let aa = input.value.files[0].name.split(".");
    if (
      aa[aa.length - 1] == "jpg" ||
      aa[aa.length - 1] == "bmp" ||
      aa[aa.length - 1] == "png" ||
      aa[aa.length - 1] == "jpeg" ||
      aa[aa.length - 1] == "webp"
    ) {
      const data = new FormData();
      data.append("file", input.value.files[0]);
      data.append("id", store.user.id);
      data.append("realname", store.user.realname);
      $axios
        .post("/user/update", data, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          console.log(res);
          store.setUserAvatar(res.data.data);
          Bus.$emit("finishChange", "success");
        });
    } else {
      alert("只允许jpg,jepg,png,bmp, webp格式的图片");
      Bus.$emit("finishChange", "error");
    }
  }
};
const showPicture = () => {
  let url = window.webkitURL || window.URL;
  let imgfileurl: string = "";
  if (input.value)
    imgfileurl = input.value.files ? url.createObjectURL(input.value.files[0]) : "";
  ImgSrc.value = imgfileurl;
};
</script>

<style lang="scss" scoped>
.img {
  display: flex;
  justify-content: space-between;
  align-items: center;
  button {
    border: 2px solid black;
    width: 50px;
    height: 30px;
    outline: none;
    border-radius: 30px;
    transition: all 0.4s;
    &:hover {
      background-color: black;
      color: #fff;
    }
  }
}
#Box {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  background-color: #fff;
  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}
input {
  display: none;
}
</style>
